package com.gabriellaet.subtitle
{	
	import flash.events.EventDispatcher;
	import com.gabriellaet.string.trim;
	
	public class SRT extends EventDispatcher
	{
		public var subtitles:Subtitle;
		
		public function SRT()
		{
		}
		
		public function parse(data:String):Boolean
		{
			subtitles = new Subtitle();
			
			const BLOCK_REGEX:RegExp = /\n\r?\n/;
			const ROW_REGEX:RegExp = /\r?\n/;
			const TIME_REGEX:RegExp = /(\d{2}:\d{2}:\d{2}(?:,\d*)?) --> (\d{2}:\d{2}:\d{2}(?:,\d*)?)/;
			
			var blocks:Array = data.split(BLOCK_REGEX);
			var size:int = blocks.length;
			var s:Subtitle = subtitles;
			
			for(var i:int = 0; i<size; i++){
				if(trim(blocks[i]) == "") continue;
				if(i > 0) s = s.next = new Subtitle();
				
				var rows:Array = blocks[i].split(ROW_REGEX);
				
				if(isNaN(rows[0])){
					throw new Error("[SRT] Subtitle index is not a valid number");
					return false;
				}
				
				var time:Array;
				if(!(time = rows[1].match(TIME_REGEX))){
					throw new Error("[SRT] Invalid time format: "+rows[1]);
					return false;
				}
				
				s.start = new Timestamp(time[1]);
				s.end = new Timestamp(time[2]);
				s.text = rows.slice(2, rows.length).join("\n");
			}
			
			return true;
		}
		
		public function get(time:Number=0.0):Subtitle
		{
			var s:Subtitle = subtitles;
			while(s){
				if(time >= s.start.value && time <= s.end.value){
					return s;
				}
				s = s.next;
			}
			
			return null;
		}
	}
}